<?php 
include ("../includes/config_conexao.php");

$idServico = $_GET['id'];

$sql = "SELECT s.id_servico, a.id_atendimento, c.desc_cliente, s.assunto_servico, s.vlr_servico, s.vlr_desc_servico,
		      s.id_tipo_pagamento,date_format(s.data_pag_servico,'%d/%m/%Y') data_pag_servico,s.vlr_pag_servico,
		      date_format(s.data_prev_servico,'%d/%m/%Y') data_prev_servico, s.hr_prev_exec_servico,
		      sa.id_status, sa.desc_status, s.id_usuario, TIME_FORMAT(a.hora_inicio,'%H:%i') hora_inicio, TIME_FORMAT(a.hora_termino,'%H:%i') hora_termino,
		      u.desc_usuario, tp.desc_tipo_pagamento
		FROM servico s
		INNER JOIN atendimento a ON s.id_servico = a.id_servico
		INNER JOIN historico_atendimento ha ON a.id_atendimento = ha.id_atendimento
		INNER JOIN cliente c ON s.id_cliente = c.id_cliente 
		INNER JOIN status_atendimento sa ON ha.id_status = sa.id_status
		LEFT JOIN usuario u ON s.id_usuario = u.id_usuario
		LEFT JOIN tipo_pagamento tp ON tp.id_tipo_pagamento = s.id_tipo_pagamento
		WHERE s.status_servico = 'A'
		    AND s.id_servico = {$idServico}
		ORDER BY ha.data_inc_historico desc
		LIMIT 1";

$result = mysql_query($sql);
$linha = mysql_fetch_array($result);
$idUsuario = $linha['id_usuario'];
$nomeUsuario = $linha['desc_usuario'];
$idStatusAtendimento = $linha['id_status'];
$idAtendimento = $linha['id_atendimento'];
$hora_inicio = $linha['hora_inicio'];
$hora_termino = $linha['hora_termino'];
$ID_TIPO_PAGAMENTO = $linha['id_tipo_pagamento'];
$descTipoPagamento = $linha['desc_tipo_pagamento'];
$dataPagServico = $linha['data_pag_servico'];
$vlrPagServico = number_format($linha['vlr_pag_servico'],2,'.',',');


$rsHist = mysql_query("SELECT ha.desc_historico
						FROM servico s, atendimento a, historico_atendimento ha
						WHERE s.status_servico = 'A'
						    AND s.id_servico = a.id_servico
						    AND a.id_atendimento = ha.id_atendimento
						    AND s.id_servico = ".$idServico." ORDER BY ha.data_inc_historico DESC");

$rsPecas = mysql_query("select s.id_servico, p.id_peca, cp.desc_categoria, p.desc_peca,
						        p.vlr_normal, mp.qtd_utilizada, p.vlr_normal * mp.qtd_utilizada as vlr_total
						from servico s
						left join movimento_peca mp on mp.id_servico = s.id_servico
						inner join peca p on p.id_peca = mp.id_peca
						inner join categoria_peca cp on cp.id_categoria = p.id_categoria
						where s.id_servico = ".$idServico);

$rsServico = mysql_query("select e.desc_especialidade, te.desc_tipo_especialidade
						from servico s, serv_tipo_especialidade ste, tipo_especialidade te, especialidade e
						where s.status_servico = 'A'
							and s.id_servico = ste.id_servico
							and ste.id_tipo_especialidade = te.id_tipo_especialidade  
							and te.id_especialidade = e.id_especialidade
							and s.id_servico = ".$idServico);


$strHtml = '
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<table style="width:900px">
	<tr>
		<td style="width:130px">Cliente:</td>
		<td>'.$linha["desc_cliente"].'</td>
	</tr>
	<tr>
		<td style="width:130px">Data/Hora marcada:</td>
		<td>'. $linha["data_prev_servico"].' '.$linha["hr_prev_exec_servico"].'</td>
	</tr>
	<tr>
		<td style="width:130px">Status servi&ccedil;o:</td>
		<td>'.$linha['desc_status'].'</td>
	</tr>
	<tr>
		<td style="width:130px" valign="top">Descrição do servi&ccedil;o:</td>
		<td>
			'.$linha['assunto_servico'].'
		</td>
	</tr>
	<tr>
		<td style="width:130px">Valor do servi&ccedil;o: </td>
		<td>
			'.number_format($linha['vlr_servico'],2,',','.').'
		</td>
	</tr>
	<tr>
		<td style="width:130px">Valor com desconto: </td>
		<td>
			'.number_format($linha['vlr_desc_servico'],2,',','.').'
		</td>
	</tr>
	<tr>
		<td style="width:130px;vertical-align:top;">Servi&ccedil;o:</td>
		<td>
		';


			while($linhaServ = mysql_fetch_array($rsServico)){
				$strHtml .= $linhaServ['desc_especialidade']." - ".$linhaServ['desc_tipo_especialidade']."<br />";
			}
			
			
$strHtml .=	'
		</td>
	</tr>
	<tr>
		<td style="width:130px;vertical-align:top;">Hist&oacute;rico:</td>
		<td>
			<table id="TabelaHistorico" width="500px">
				'; 

					while($linhaHist = mysql_fetch_array($rsHist)){
						$strHtml .= "<tr><td  style='border-bottom: 1px solid #CECECE;'>".$linhaHist['desc_historico']."</td></tr>";
					}
		$strHtml .= "<tr><td  style='border-bottom: 1px solid #CECECE;'>".$linhaHist['desc_historico']."</td></tr>";
						
$strHtml .=	'
			</table>
		</td>
	</tr>
    <tr>
    	<td colspan="2"  style="padding-top:20px;">
    		<table id="TabelaPecas2" style="width:500px;">
				<thead>
					<tr style="background-color: #6CF; color:#000; font-style:italic;">
						<th align="center">Categoria Peça</th>
						<th align="center">Peça</th>
						<th align="center">Valor unitário</th>
						<th align="center">Qtd</th>
						<th align="center">Valor total</th>
					</tr>
				</thead>
				<tbody style="text-align:center;">';

					if (!empty($rsPecas)) { 
						$cont = 1;
						while($val = mysql_fetch_array($rsPecas)) {
							$strHtml .=	'<tr id="'.$cont.'">
												<td align="center">'.$val['desc_categoria'].'</td>
												<td align="center">'.$val['desc_peca'].'</td>
												<td align="center">'.number_format($val['vlr_normal'],'2',',','.').'</td>
												<td align="center">'.$val['qtd_utilizada'].'</td>
												<td align="center">'.number_format($val['vlr_total'],'2',',','.').'</td>
											</tr>';
					$cont++; }
					}
					
		$strHtml .= "<tr><td style='border-bottom: 1px solid #CECECE;'></td></tr>";
				
$strHtml .=	'	</tbody>
			</table>
    	</td>
	</tr>
	<tr>
		<td style="width:130px;padding-top:20px;">Atribu&iacute;do ao t&eacute;cnico:</td>
		<td>
			<font>'.$nomeUsuario.'</font>
		</td>
	</tr>
	<tr>
		<td style="width:130px">Hora in&iacute;cio:</td>
		<td>
			<font>'.$hora_inicio.'</font>
		</td>
	</tr>
	<tr>
		<td style="width:130px">Hora final:</td>
		<td>
			<font>'.$hora_termino.'</font>
		</td>
	</tr>
	<tr>
		<td style="width:130px">Forma de pagamento:</td>
		<td>
			<font>'.utf8_encode($descTipoPagamento).'</font>
		</td>
	</tr>
	<tr>
		<td style="width:130px">Data pagamento:</td>
		<td>
			<font>'.$dataPagServico.'</font>
		</td>
	</tr>
	<tr>
		<td style="width:130px">Valor pagamento:</td>
		<td>
			<font>'.number_format($vlrPagServico,2,',','.').'</font>
		</td>
	</tr>
</table>
';




/*********************** INICIO RELATORIO ***********************/
require_once('../includes/tcpdf/config/lang/eng.php');
require_once('../includes/tcpdf/tcpdf.php');

//create new PDF document
$pdf = new TCPDF("L", PDF_UNIT, PDF_PAGE_FORMAT, true, "utf-8", false); 

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('SISAT');
$pdf->SetTitle('SERVIÇO');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// capturando data do relatorio
$data = "Data: " . date("d/m/Y");
            
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH,  utf8_encode("SISAT - Sistema de Atendimento Externo"), 
                    utf8_encode("
                                <b>Relat&oacute;rio Gerencial</b>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                {$data}")  );

//set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

//set margins
$pdf->SetMargins(5, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 

//set some language-dependent strings
$pdf->setLanguageArray($l); 

// ---------------------------------------------------------

$pdf->SetFont('dejavusans', '', 7);
$pdf->AddPage();

                        
$pdf->writeHTML($strHtml, true, 0, true, 0);
$pdf->lastPage(); 
$pdf->Output('servico.pdf', 'I');

//echo $strHtml;            
/*********************** FIM RELATORIO **************************/